package com.summer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.summer.entity.TbScoreProve;
import com.summer.entity.TbUserinfo;
import com.summer.mapper.TbScoreProveMapper;
import com.summer.utils.JwtToken;
import com.summer.utils.MyUtil;
import com.summer.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *前端控制器未测试
 * @author summer502
 * @since 2021-03-31
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping("/tb-score-prove")
@Api(value = "TbScoreProveController", description = "活动加分证明api")
public class TbScoreProveController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required = false)
    TbScoreProveMapper tbScoreProveMapper;
    /**
     * 管理员加分证明图片上传
     *
     * @param request
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @ApiOperation("管理员加分证明图片上传")
    @PostMapping("/web/AddTbScoreProve")
    @ResponseBody
    public ResponseEntity AddTbScoreProve(@RequestParam(required = true) MultipartFile prove_url,
                                     @RequestParam(required = false) String prove_description,
                                     @RequestParam(required = true) int activityId,
                                     @RequestParam(required = false) String topic,
                                     @RequestParam(required = false) int userId,
                                     HttpServletRequest request,
                                     @RequestHeader String Authorization,
                                     HttpServletResponse response) throws IOException, ParseException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        if (user.getRoleId()!=1){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        //图片资源访问路径
        String fileLocation = "/static/restaurantRes/";
        //获取提交文件名称
        String filename = prove_url.getOriginalFilename();
        String newfilename = System.currentTimeMillis() + UUID.randomUUID().toString().replace(".", "").substring(0, 6) + "." + filename.substring(filename.lastIndexOf(".") + 1);

        //定义上传文件存放的路径
        String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
        System.out.println(path);
        //返回保存的url，根据url可以进行文件查看或者下载
        String filePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() //端口 https443端口无需添加
                + fileLocation + newfilename;

        String head_portrait = filePath;//根路径+文件名
        File file = new File("/www/javaweb/propaganda_system/picture/" + newfilename);
        TbScoreProve tbScoreProve = new TbScoreProve();
        tbScoreProve.setProveUrl(head_portrait);
        tbScoreProve.setActivityId(activityId);
        tbScoreProve.setUserId(userId);
        tbScoreProve.setTopic(topic);
        tbScoreProve.setProveDescription(prove_description);
//            //修改信息
//            pictureDao.updateById(picture);
        tbScoreProveMapper.insert(tbScoreProve);
        prove_url.transferTo(file);
        responseEntity = ResponseEntity.ok();
        TbScoreProve tbScoreProve1=tbScoreProveMapper.selectById(tbScoreProve.getProveId());
        responseEntity.putDataValue("tbScoreProve",tbScoreProve1);
        System.out.println("加分证明上传成功");
        return responseEntity;
    }

    /**
     * 查看自己的加分证明列表
     * @return
     */
    @ApiOperation("查看自己的加分证明列表")
    @PostMapping("/web/selectTbScoreProveList")
    @ResponseBody
    public ResponseEntity selectTbScoreProveList(@RequestHeader String Authorization) throws IOException {
        ResponseEntity responseData = null;
//        int is_delete = 0;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        QueryWrapper<TbScoreProve> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getUserId());
        List<TbScoreProve> list=tbScoreProveMapper.selectList(queryWrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("list", list);
        return responseData;
    }

    /**
     * 管理员加分证明删除
     * @param Authorization
     * @param prove_id
     * @return
     * @throws IOException
     */
    @ApiOperation("管理员加分证明删除")
    @PostMapping("/web/deleteTbScoreProve")
    @ResponseBody
    public ResponseEntity deleteTbScoreProve(@RequestHeader String Authorization, @RequestParam(required = true) Integer prove_id) throws IOException {
        ResponseEntity responseEntity = null;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        if (user.getRoleId()!=1){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        int is_delete = 1;
        TbScoreProve tbScoreProve = tbScoreProveMapper.selectById(prove_id);
        tbScoreProve.setIsDelete(is_delete);
        tbScoreProveMapper.updateById(tbScoreProve);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("msg", "删除成功");
        return responseEntity;
    }

    /**
     * 管理员查看所有的加分证明列表
     * @return
     */
    @ApiOperation("管理员查看所有的加分证明列表")
    @PostMapping("/web/selectTbScoreProve1")
    @ResponseBody
    public ResponseEntity selectTbScoreProve1(@RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity ;
//        int is_delete = 0;
        String token = Authorization;
        //通过token解密出来的user对象
        TbUserinfo user = JwtToken.unsign(token, TbUserinfo.class);
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        if (user.getRoleId()!=1){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        QueryWrapper<TbScoreProve> queryWrapper = new QueryWrapper<>();
       // queryWrapper.eq("user_id", user.getUserId());
        List<TbScoreProve> list=tbScoreProveMapper.selectList(queryWrapper);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("list", list);
        return responseEntity;
    }

}
